<?php
namespace App\Http\Controllers;

use App\admin\Service\OA;
use App\Models\Admin\CategoryModel;
use App\Models\Admin\UserAccessModel;
use App\Services\Admin\OrderService;
use App\Services\Admin\UserService;
use App\Services\Finance\FinanceRecordService;
use App\Utilities\Utility;
use Illuminate\Support\Facades\Redis;

class BaseController extends Controller
{
    /**
     * 自定义基本控制器
     */

    public function __construct()
    {
        OA::load();
        defined('DOMAIN') or define('DOMAIN',env('DOMAIN')); //域名常量
    }

    /**
     * curl请求
     * $url地址、$mehod方法、$type格式、$string数据
     */
    public function getCurl($url,$method='get',$type='json',$string='')
    {
        $curl = curl_init(); //初始化
        //设置参数
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        if ($method=='post') {
            curl_setopt($curl,CURLOPT_POST,1);
            curl_setopt($curl,CURLOPT_POSTFIELDS,$string);
        }
        $output = curl_exec($curl); //采集
        if ($type=='json') {
//            echo curl_errno($curl);
//            if (curl_errno($curl)) {
//                return curl_errno($curl);
//            } else {
//                return json_decode($output,true);
//            }
            if (curl_errno($curl)) { return false; }
            return json_decode($output,true);
        }
    }

    /**
     * 新增用户TOKEN
     * 制作者：九哥
     */
    public function accessSet($uid)
    {
        exit("弃用");
        /*
        $start = strtotime(date('Ymd').'000000');
        $end = strtotime(date('Ymd').'235959');
        $model = UserAccessModel::where('uid',$uid)
            ->where('created_at','>',$start)
            ->where('created_at','<=',$end)
            ->select('token')
            ->first();
        if ($model) { return $model->token; }
        $token = Utility::getRandStr(rand(60,80));
        $dataArr = array(
            'uid' => $uid,
            'token' => $token,
            'created_at' => time(),
        );
        $lastId = UserAccessModel::insertGetId($dataArr);
        return $token;*/
        //$token = Utility::getRandStr(rand(60,80));


    }

    /**
     * 获取用户UID
     * 制作者：九哥
     */
    public function accessGet($token='')
    {
       // print_r($_COOKIE);exit;
        /*
        if(!empty($_COOKIE['token'])){
            $token=$_COOKIE['token'];
        }
        $model = UserAccessModel::where('token',$token)
            ->orderBy('id','desc')
            ->first();
        if (!$model) { return 0; }
        return $model->uid;*/
        return OA::$user->getId();
    }

    /**
     * 获取用户TOKEN
     * 制作者：九哥
     */
    public function accessGetByUid($uid)
    {
        $model = UserAccessModel::where('uid',$uid)
            ->orderBy('id','desc')
            ->first();
        return $model->uid;
    }

    /**
     * 根据用户经纬度lng、lat，获取用户矩形4个点的经纬度，用于SQL查询排序
     *@param lng float 经度
     *@param lat float 纬度
     *@param distance float 该点所在圆的半径，该圆与此正方形内切，默认值为0.5千米
     *@return array 正方形的四个点的经纬度坐标
     */
    public function getSquarePoint($lng, $lat,$distance = 10)
    {
        $earthdata=6371;//地球半径，平均半径为6371km
        $dlng =  2 * asin(sin($distance / (2 * $earthdata)) / cos(deg2rad($lat)));
        $dlng = rad2deg($dlng);
        $dlat = $distance/$earthdata;
        $dlat = rad2deg($dlat);
        $arr = array(
            'left_top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
            'right_top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
            'left_bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
            'right_bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
        );
        return $arr;
    }

    /**
     * 腾讯地图，通过2坐标计算距离
     *@param lngStart float 经度
     *@param latStart float 纬度
     *@param lngEnd float 经度
     *@param latEnd float 纬度
     *@return array 正方形的四个点的经纬度坐标
     */
    public function getDistanceByPoints($lngStart,$latStart,$lngEnd,$latEnd)
    {
        // GET请求：http://apis.map.qq.com/ws/distance/v1/?mode=driving&from=39.983171,116.308479&to=39.996060,116.353455;39.949227,116.394310&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77
        $mode = 'driving'; //出行方式
        //第三方地图腾讯地图,九哥申请的：
        $map_key = 'JWYBZ-7LK3K-KRNJA-AGOHX-CIZNK-RCFXV';
        $pointStart = $lngStart.','.$latStart;
        $pointEnd = $lngEnd.','.$latEnd;
        $url = 'http://apis.map.qq.com/ws/distance/v1/?mode='.$mode.'&from='.$pointStart.'&to='.$pointEnd.'&key='.$map_key;
        $string = '';
        $res = $this->getCurl($url,'get','json',$string);
        if ($res['status']!=0 ||
            !isset($res['result']['elements'][0]['distance'])) {
            return false;
        }
        return $res['result']['elements'][0]['distance'];
    }

    /**
     * 获取redis
     */
    public function getRedisStr($key)
    {
        if(Redis::exists($key)) {
            return Redis::get($key);
        } else {
            return '';
        }
    }

    /**
     * 获取redis
     */
    public function getRedis($key)
    {
        if(Redis::exists($key)) {
            $result = Redis::get($key);
            return unserialize($result);
        } else {
            return '';
        }
    }

    /**
     * 设置redis，值为字符串
     */
    public function setRedisStr($key,$value)
    {
        return Redis::setex($key, $this->redisPeriod, $value);
    }

    /**
     * 设置redis
     */
    public function setRedis($key,$value)
    {
        return Redis::setex($key, $this->redisPeriod, serialize($value));
    }

    /**
     * 删除redis
     */
    public function delRedis($key)
    {
        return Redis::del($key);
    }

    /**
     * 获取分类子集
     */
    public function getSubsByCates($pids)
    {
        return CategoryModel::getSubsByCates($pids);
    }

    /**
     * 平台内部支付
     * 订单相关支付，先放平台担保；其他支付直接付款到账
     * @param $paySend 付款方UID
     * @param $payAccept 收款方UID
     * @param $genre 交易类型：
     *          1订单保证金，2订单预付款，3订单余款支付，4工资发放，
     * @param $orderId 订单ID，适用于genre小于4；当genre等于4，orderId则为0
     * @param $money 支付金额，元
     */
    public function setPlatPay($paySend,$payAccept,$genre,$orderId=0,$money)
    {
        $userObj = new UserService();
        $recordObj = new FinanceRecordService();
        $orderObj = new OrderService();
        $user = $userObj->getOne($paySend);
        $user2 = $userObj->getOne($payAccept);
        if (!$user) {
            return array('code'=>'-1','msg'=>'付款方账户不存在！');
        }
        if (!$user2) {
            return array('code'=>'-2','msg'=>'收款方账户不存在！');
        }
        if (!in_array($genre,[1,2,3,4])) {
            return array('code'=>'-3','msg'=>'交易类型错误！');
        }
        $order = $orderObj->getOne($orderId);
        if ($genre<4 && !$order) {
            return array('code'=>'-4','msg'=>'订单交易错误！');
        }
        if ($user->finance=='0.00' || $user->finance<$money) {
            return array(
                'code' => '-5',
                'msg' => '付款方账户余额不足，请按照以下地址去充值！',
                'link' => DOMAIN.'/h5/my/account.html',
            );
        }
        /**
         * 这里下面最好用事务
         */
        //创建交易记录
        $recordArr = array(
            'payer' => $paySend,
            'receiver' => $payAccept,
            'genre' => $genre,
            'order_id' => $orderId,
            'money' => $money,
        );
        $lastRecordId = $recordObj->setAdd($recordArr);
        if (in_array($genre,[4,5])) {
            //减少付款方余额
            $resFinance = $userObj->setPayerFinance($paySend,$money);
            //增加收款方余额、收益
            $resFinance2 = $userObj->setReceiver($payAccept,$money);
        }
        return array(
            'code' => '0',
            'msg' => '付款成功！',
        );
    }

    /**
     * 支付到账
     * 订单类支付
     */
    public function setTradeFinishBasic($orderId)
    {
        $recordObj = new FinanceRecordService();
        $model = $recordObj->getOneByOrder($orderId,2);
        if (!$model) { return false; }
//        return array('code'=>-1, 'msg'=>'支付不存在或已到账！');
        $data = array(
            'status' => 3,
        );
        $recordObj->setModify($data,$orderId);
        return true;
    }

    /**
     * 获取接口调用权限
     * @param $plat 调用平台，1APP，2PC
     */
    public function getApiAccess($plat)
    {
        $apiAccessObj = new \App\Models\Main\ApiAccessModel();
        return $apiAccessObj->getApiAccess($plat);
    }
}
